#!/bin/sh
# SpaceCast init script.
. /etc/utils.sh

# Set the stack size to 256KB (Default to 8M) to avoid OOM issues.
# When CGO is enabled, each blocking syscall (Read, Write) will call
# pthread_create to create a new thread, so stack size for 100 concurrent
# streams would be 800MB and the memory limit would be hit without this change.
ulimit -s 256

APP="spacecast"
BINARY="/app/spacecast/appliance"
FLAGS="-logtostderr -ring_buffer_size=64MB"
if [ -e /tmp/DEBUG ]; then
  FLAGS="$FLAGS -debug=true"
fi

running() {
  [ -n "$(pgrep -f "$BINARY")" ]
}

case "$1" in
  start)
    if running; then
      echo "SpaceCast is already running!"
    else
      (
        # Check for critical software updates
        wait-until-created /tmp/gpio/ledcontrol/update_check_complete
        # Bootstrap
        wait-until-created /tmp/gpio/bootstrap
        # Service file
        wait-until-created /config/service_file
        babysit_start 10 "$APP" "$BINARY" "$FLAGS"
      ) &
      echo "SpaceCast started."
    fi
    ;;
  stop)
    pkill -f "$BINARY"
    while running; do
      echo "SpaceCast is in lameduck mode. Please wait..."
      sleep 10
    done
    echo "SpaceCast stopped."
    ;;
  restart|reload)
    $0 stop;$0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac
